package com.archeanx.lib.http;

import android.util.Log;

import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 获取一个retrofit实例
 */
public abstract class XOnHttpRequestInitListener {

    private static OkHttpClient okHttpClient;
    /**
     * 是否打印头部日志
     */
    private static boolean isShowHeadLogging = false;
    /**
     * 是否打印身体日志
     */
    private static boolean isShowBodyLogging = false;

    public static void enableLogging(boolean isShowHeadLog, boolean isShowBodyLog) {
        isShowBodyLogging = isShowHeadLog;
        isShowHeadLogging = isShowBodyLog;
    }


    public Retrofit getRetrofit(String baseUrl) {
        return new Retrofit.Builder()
                .client(getOkHttp())
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    public OkHttpClient getOkHttp() {
        if (okHttpClient == null) {
            okHttpClient = getOkhttpBuilder().build();
        }
        return okHttpClient;
    }

    public OkHttpClient.Builder getOkhttpBuilder() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .cookieJar(new XCookieJarImpl())
                //https配置
                .sslSocketFactory(XHttpUtil.getSSLSocketFactory(), XHttpUtil.trustManager)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .connectTimeout(3, TimeUnit.SECONDS)
                //强制增加一个标识android
                .addInterceptor(new XUserAgentInterceptor("Android" + XUserAgentInterceptor.getUserAgent()));
        if (isShowBodyLogging) {
            builder.addNetworkInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("---Http-body--", message);
                }
            }).setLevel(HttpLoggingInterceptor.Level.BODY));
        }
        if (isShowHeadLogging) {
            builder.addNetworkInterceptor(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
                @Override
                public void log(String message) {
                    Log.d("---Http-head--", message);
                }
            }).setLevel(HttpLoggingInterceptor.Level.HEADERS));
        }
        return builder;
    }


}
